import {
  Controller,
  Get,
  Post,
  Body,
  Param,
  Delete,
  Request,
  UseGuards,
  Query,
} from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
import { FeedsService } from './feeds.service';
import { Feed } from './feed.entity';

@Controller('feeds')
export class FeedsController {
  constructor(private readonly feedsService: FeedsService) {}

  // 发布动态
  @UseGuards(AuthGuard('jwt'))
  @Post()
  async createFeed(@Request() req, @Body() feedData: Partial<Feed>) {
    try {
      const userId = parseInt(req.user.id);
      const feed = await this.feedsService.createFeed(userId, feedData);
      return {
        success: true,
        data: feed,
        message: '动态发布成功',
      };
    } catch (error) {
      return {
        success: false,
        data: null,
        message: '动态发布失败: ' + error.message,
      };
    }
  }

  // 获取动态列表
  @UseGuards(AuthGuard('jwt'))
  @Get()
  async getFeeds(
    @Query('page') page: number = 1,
    @Query('limit') limit: number = 10,
  ) {
    try {
      const feeds = await this.feedsService.getFeeds(page, limit);
      return {
        success: true,
        data: feeds,
        message: '获取动态列表成功',
      };
    } catch (error) {
      return {
        success: false,
        data: [],
        message: '获取动态列表失败: ' + error.message,
      };
    }
  }

  // 根据用户ID获取动态
  @UseGuards(AuthGuard('jwt'))
  @Get('user/:userId')
  async getFeedsByUserId(@Param('userId') userId: string) {
    try {
      const feeds = await this.feedsService.getFeedsByUserId(parseInt(userId));
      return {
        success: true,
        data: feeds,
        message: '获取用户动态成功',
      };
    } catch (error) {
      return {
        success: false,
        data: [],
        message: '获取用户动态失败: ' + error.message,
      };
    }
  }

  // 根据ID获取动态
  @UseGuards(AuthGuard('jwt'))
  @Get(':id')
  async getFeedById(@Param('id') id: string) {
    try {
      const feed = await this.feedsService.getFeedById(parseInt(id));
      if (!feed) {
        return {
          success: false,
          data: null,
          message: '动态不存在',
        };
      }
      return {
        success: true,
        data: feed,
        message: '获取动态成功',
      };
    } catch (error) {
      return {
        success: false,
        data: null,
        message: '获取动态失败: ' + error.message,
      };
    }
  }

  // 删除动态
  @UseGuards(AuthGuard('jwt'))
  @Delete(':id')
  async deleteFeed(@Request() req, @Param('id') id: string) {
    try {
      const userId = parseInt(req.user.id);
      const result = await this.feedsService.deleteFeed(parseInt(id), userId);
      if (!result) {
        return {
          success: false,
          data: null,
          message: '动态不存在或无权限删除',
        };
      }
      return {
        success: true,
        data: null,
        message: '动态删除成功',
      };
    } catch (error) {
      return {
        success: false,
        data: null,
        message: '动态删除失败: ' + error.message,
      };
    }
  }
}
